package com.adxnz.dev.selenium;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Splitter;

/**
 * 企业微信离职分配
 * 
 * @author worley
 */
public class HelloSelenium {

    public static void main(String[] args) {
        System.setProperty("webdriver.edge.driver", "target\\classes\\msedgedriver.exe");

        EdgeDriver driver = new EdgeDriver();

        Options opt = driver.manage();
        opt.window().maximize();
        // 访问企业微信首页
        driver.get("https://work.weixin.qq.com");
        // 设置已登录的Cookie
        // https://work.weixin.qq.com/wework_admin/loginpage_wx
        setCookies(opt);
        driver.get("https://work.weixin.qq.com/wework_admin/frame#customer/pending");
        new WebDriverWait(driver, Duration.ofMinutes(1)).until(d -> {
            // 点击：查询已离职成员
            WebElement element = d.findElement(By.xpath(
                    "/html/body/div[1]/div/div/main/div/div[3]/div[2]/div[1]/div[2]/div/div[2]/div/div[1]/div[2]/div/a/span[1]"));
            driver.executeScript("arguments[0].click()", element);
            // 搜索离职成员
            driver.findElement(By.id("memberSearchInput")).sendKeys("何碧");
            return new WebDriverWait(driver, Duration.ofMinutes(1));
        }).until(d -> {
            long endTime = System.currentTimeMillis() + 1000;
            return new WebDriverWait(driver, Duration.ofMinutes(1)).until(dd -> {
                if (System.currentTimeMillis() < endTime) {
                    System.out.println("等待渲染...");
                    return null;
                }
                List<WebElement> list = driver
                        .findElements(By.xpath("/html/body/div[3]/div/div[2]/div/div/div/div[1]/div[1]/div[4]/ul/li"));
                System.out.println("渲染完成：" + list);
                // 选中全部离职成员
                list.forEach(WebElement::click);
                return new WebDriverWait(driver, Duration.ofMinutes(1));
            });
        }).until(d -> {
            // 点击确认
            driver.executeScript("arguments[0].click()",
                    driver.findElement(By.xpath("/html/body/div[3]/div/div[3]/a[1]")));
            long endTime = System.currentTimeMillis() + 1000;
            return new WebDriverWait(driver, Duration.ofMinutes(1)).until(dd -> {
                if (System.currentTimeMillis() < endTime) {
                    System.out.println("等待中...");
                    return null;
                }
                return new WebDriverWait(driver, Duration.ofMinutes(1));
            });
        }).until(d -> {
            // 选中第一个离职导购
            WebElement element = d.findElement(By.xpath(
                    "/html/body/div[1]/div/div/main/div/div[3]/div[2]/div[1]/div[2]/div/div[4]/div/table/tbody/tr[1]/td[1]/input"));
            element.click();
            return new WebDriverWait(driver, Duration.ofMinutes(1)).until(dd -> {
                if (element.isSelected()) {
                    System.out.println("已选中：" + element);
                    return new WebDriverWait(driver, Duration.ofMinutes(1));
                }
                System.out.println("未选中：" + element);
                return null;
            });
        }).until(d -> {
            // 点击：分配给其他成员
            driver.findElement(By.xpath("/html/body/div[1]/div/div/main/div/div[3]/div[2]/div[1]/div[2]/div/div[3]/a"))
                    .click();
            return new WebDriverWait(driver, Duration.ofMinutes(1));
        }).until(d -> null);
        driver.quit();
    }

    private static void setCookies(Options opt) {
        String cookieStr = "eas_sid=C147d0s322y9n3l3Y3H5x9h9J2; RK=jK0BcTmtGu; ptcz=95c3d5746d9fa282ebbf4da7d15ffa3ee11e4955586ba02e30c3281cbdd5a633; pgv_pvid=804882493; wwrtx.c_gdpr=0; wwrtx.i18n_lan=zh; wwrtx.ref=direct; wwrtx.refid=0319114; wwrtx.vst=T6lDloaJl_hEBnF6UxIxt7-MGw8FZq_GkPfGtgVOD5iBSLrco8jPwHQazt5dcqoB1qCFyervxGbro5U16PNIz4lMGWBaq0dt6_Gre81uK2fmbVCz-Okx3bcITuGOUJ8Jk08wxBn1UtKysV_APnxwOaEUIlBBSH7o85ftloPLTvF93qkmsUeAc7dN2_mVxaKwItQE9H0YP9FWdROAyeON4NEaT7VhHhg-Njkg2E6TX7Moa2GkTD9gm93UBELuS6LeL1k09I8g4bv4uO8gXJwAqg; wwrtx.d2st=a1119498; wwrtx.sid=08Cu_Q-u7ELBaZ7cUiv-_tGNA3pUN1CGhVSu7whsi8UwHpFgZxZNHcP1CJzb40Qp; wwrtx.ltype=1; wwrtx.vid=1688858385457034; wxpay.corpid=1970325111086474; wxpay.vid=1688858385457034; wwrtx.cs_ind=; wwrtx.logined=true";
        cookieStr.split(cookieStr);
        Map<String, String> cookieMap = Splitter.on(";").trimResults().omitEmptyStrings().withKeyValueSeparator("=")
                .split(cookieStr);
        cookieMap.entrySet().stream()
                .map(entry -> new Cookie.Builder(entry.getKey(), entry.getValue()).domain(".qq.com").build())
                .forEach(opt::addCookie);
    }
}
